import csv
import logging
import StringIO

from db import model
from google.appengine.ext import db
from model import Answer
from model import FriendSurvey
from model import StrainedFriendSurvey
from student_client import StudentClient
from survey_client import SurveyClient


QUESTION_IDS = [
  'dorm_talk', 'father_work', 'major', 'ideo', 'floor_good', 'sporting_event)',
  'social_bias', 'library', 'dorm_nobody', 'marywood_event', 'clubs',
  'floor_emergency', 'music_tastes', 'dorm_staff', 'dorm_frpart', 'tv_time',
  'study_time', 'cafeteria', 'dorm_problem', 'dorm_good', 'floor_staff',
  'dorm_program', 'floor_talk', 'excercise', 'study_area', 'gpa', 'crime',
  'religion', 'race', 'semesters', 'overall_trust', 'dorm_meeting', 'reader',
  'campus_computer_labs', 'dorm_help', 'happy', 'second_major', 'classroom',
  'floor_help','first_stop','school_year','religion_strength','study_grounds',
  'gym','atrium_diner','butt_hut','www_time','sports','floor_problem',
  'dorm_trust', 'lounges', 'laundry_room', '24hr_lobby', 'floor_frpart',
  'dorm_nofriends', 'marian_chael', 'dorm_similar', 'dorm_kitchen',
  'floor_nobody', 'gender', 'age', 'floor_trust', 'mother_work',
  'student_center', 'hispanic', 'floor_nofriends', 'weekends_home', 'smoke',
  'computer_lab', 'the_connection', 'dorm_emergency', 'floor_similar'
]


class ExportTable(object):
  ANSWER = 'Answer'
  FRIEND_SURVEY = 'FriendSurvey'
  STRAINED_FRIEND_SURVEY = 'StrainedFriendSurvey'
  STUDENT = 'Student'
  STUDENT_SESSION = 'StudentSession'


class ExportClient(object):
  def __init__(self):
    self.student_client = StudentClient()
    self.survery_client = SurveyClient()

  def exportStudents(self):
    students = self.student_client.getStudents()

    header = [
      'Student Id',
      'Email Address',
      'First Name',
      'Middle Name',
      'Last Name',
      'Current Session'
    ]

    students_export = ','.join(header) + '\n'

    for student in students:
      export_data = [
        str(student.key().id()),
        student.email_address,
        student.first_name,
        student.middle_name,
        student.last_name,
        student.current_session
      ]
      students_export += self.__exportRow(export_data)

    return students_export

  def exportStudentSessions(self, session):
    student_sessions = self.student_client.getAllSessionData(session=session)

    header = [
      'Student Id',
      'Session',
      'Dorm',
      'Room',
      'R/A',
      'Status',
      'Previous Session Status',
      'Consented'
    ]

    student_sessions_export = ','.join(header) + '\n'

    for student_session in student_sessions:
      export_data = [
        str(student_session.student_id),
        student_session.session,
        student_session.dorm,
        student_session.room,
        student_session.ra,
        student_session.status,
        student_session.previous_session_status,
        student_session.consented
      ]
      student_sessions_export += self.__exportRow(export_data)

    return student_sessions_export

  def exportAnswers(self, session):
    answers = self.survery_client.getAnswers(session=session)

    header = [
      'Answer Id',
      'Student Id',
      'Session',
      'Section Id',
      'Question Id',
      'Values',
      'Other Value'
    ]

    answers_export = ','.join(header) + '\n'

    for answer in answers:
      export_data = [
        str(answer.key().id()),
        str(answer.student_id),
        answer.session,
        answer.section_id,
        answer.question_id,
        self.getAnswerValues(answer),
        self.getOtherValue(answer)
      ]
      answers_export += self.__exportRow(export_data)

    return answers_export

  def getAnswerValues(self, answer):
    value = ','.join(answer.values)
    # HACK: The value "Don't know" is causing problems.
    if value.endswith('t know'):
      value = 'DONT KNOW'    
    return value

  def getOtherValue(self, answer):
    if answer.other_value:
      return answer.other_value
    return ''

  def exportFriendSurveys(self, session, start_index, end_index):
    friend_surveys = self.survery_client.getFriendSurveys(session=session)

    header = [
      'Student Id',
      'Session',
      'Friend Id',
      'Relation Type',
      'Friendship Level',
      'Interactive Level',
      'Ask Advice Level',
      'First Met Location',
      'First Met Interaction'
    ]

    friend_surveys_export = ','.join(header) + '\n'

    for friend_survey in friend_surveys[start_index:end_index]:
      export_data = [
        str(friend_survey.student_id),
        friend_survey.session,
        str(friend_survey.friend.key().id()),
        friend_survey.relation_type,
        friend_survey.friendship_level,
        friend_survey.interaction_level,
        friend_survey.ask_advice_level,
        friend_survey.first_met_location,
        friend_survey.first_met_interation
      ]
      friend_surveys_export += self.__exportRow(export_data)

    return friend_surveys_export

  def exportStrainedFriendSurveys(self, session):
    strained_friend_surveys = self.survery_client.getStrainedFriendSurveys(
        session=session)

    header = [
      'Student Id',
      'Session',
      'Friend Id',
      'Relationship Level'
    ]

    strained_friend_surveys_export = ','.join(header) + '\n'

    for strained_friend_survey in strained_friend_surveys:
      export_data = [
        str(strained_friend_survey.student_id),
        strained_friend_survey.session,
        str(strained_friend_survey.friend.key().id()),
        strained_friend_survey.relationship_level
      ]
      strained_friend_surveys_export += self.__exportRow(export_data)

    return strained_friend_surveys_export

  def __exportRow(self, export_data):
      buffer = StringIO.StringIO()
      writer = csv.writer(buffer)
      try:
        writer.writerow(export_data)
      except UnicodeEncodeError:
        logging.info(export_data)
        return ','.join(export_data)
      return buffer.getvalue()
